<template>
  <div class="app-container" v-loading="loading">
    <div class="section">
      <div class="section-header">
        <span class="header-badge">1</span>
        <span class="header-title">账单信息</span>
      </div>
      <div class="info-panel">
        <div class="info-row">
          <div class="info-item">
            <label>账单编号</label>
            <span>{{ billDetail.billNo }}</span>
            <el-button v-if="billDetail.billType" type="text" size="small" style="margin-left: 10px; color: #409EFF;">{{ billDetail.billType }}</el-button>
          </div>
          <div class="info-item">
            <label>账单月份</label>
            <span>{{ billDetail.billMonth }}</span>
          </div>
        </div>
        <div class="info-row">
          <div class="info-item">
            <label>老人姓名</label>
            <span>{{ billDetail.elderly?.name || billDetail.name }}</span>
          </div>
          <div class="info-item">
            <label>老人身份证号</label>
            <span>{{ billDetail.elderly?.idCard || billDetail.idCard }}</span>
          </div>
        </div>
        <div class="info-row">
          <div class="info-item">
            <label>账单金额(元)</label>
            <span class="amount-value">{{ formatAmount(billDetail.billAmount) }}</span>
          </div>
          <div class="info-item">
            <label>应付金额(元)</label>
            <span class="amount-value">{{ formatAmount(billDetail.payableAmount) }}</span>
          </div>
        </div>
        <div class="info-row">
          <div class="info-item">
            <label>账单周期</label>
            <span>{{ formatBillPeriod() }}</span>
          </div>
          <div class="info-item">
            <label>共计天数(天)</label>
            <span>{{ calculateDays() }}</span>
          </div>
        </div>
        <div class="info-row">
          <div class="info-item">
            <label>交易状态</label>
            <el-tag :type="getStatusType(billDetail.transactionStatus)" size="small">{{ billDetail.transactionStatus }}</el-tag>
          </div>
          <div class="info-item">
            <label>支付截止时间</label>
            <span>{{ parseTime(billDetail.paymentDeadline, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </div>
        </div>
        <div class="info-row">
          <div class="info-item">
            <label>创建人</label>
            <span>{{ billDetail.creatorUser?.nickName || billDetail.creatorUser?.userName || billDetail.creator }}</span>
          </div>
          <div class="info-item">
            <label>创建时间</label>
            <span>{{ parseTime(billDetail.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </div>
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-header">
        <span class="header-badge">2</span>
        <span class="header-title">账单明细</span>
      </div>
      <div class="detail-panel">
        <el-table :data="detailData" style="width: 100%" size="small" border>
          <el-table-column prop="type" label="类型" width="120" align="center" />
          <el-table-column prop="itemName" label="费用项目" width="180" />
          <el-table-column prop="content" label="服务内容" />
          <el-table-column prop="amount" label="金额（元）" width="160" align="right">
            <template #default="scope">
              <span :class="{ 'amount-negative': scope.row.amount < 0, 'amount-strong': scope.row.isTotal }">
                {{ renderAmount(scope.row.amount) }}
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    
    <div class="footer-bar">
      <el-button type="primary" @click="goBack" style="background-color: #409EFF; border-color: #409EFF;">返回</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getBill } from '@/api/system/bill'
import { listBillDetailByBillId } from '@/api/system/billDetail'
import { getElderly } from '@/api/system/elderly'
import { getUser } from '@/api/system/user'
import { parseTime } from '@/utils/ruoyi'

const route = useRoute()
const router = useRouter()
const billDetail = ref({})
const loading = ref(true)

// 账单明细数据（包含汇总行，单表展示）
const detailData = ref([
  { type: '添加项', itemName: '护理费用', content: '—', amount: 0 },
  { type: '添加项', itemName: '床位费用', content: '—', amount: 0 },
  { type: '添加项', itemName: '其他费用', content: '其他', amount: 0 },
  { type: '小计', itemName: '', content: '', amount: 0, isSubtotal: true },
  { type: '扣减项', itemName: '医保支付', content: '——', amount: 0 },
  { type: '扣减项', itemName: '政府补贴', content: '——', amount: 0 },
  { type: '小计', itemName: '', content: '', amount: 0, isSubtotal: true },
  // 汇总信息
  { type: '每月应付', itemName: '', content: '', amount: 0 },
  { type: '本期应付', itemName: '', content: '', amount: 0 },
  { type: '押金', itemName: '', content: '', amount: 0 },
  { type: '账单金额', itemName: '', content: '', amount: 0 },
  { type: '预缴款支付', itemName: '', content: '', amount: 0 },
  { type: '应付金额', itemName: '', content: '', amount: 0, isTotal: true }
])

// 获取账单详情
function getBillDetail() {
  const id = route.query.id
  if (!id) {
    router.back()
    return
  }
  
  loading.value = true
  getBill(id).then(response => {
    billDetail.value = response.data
    // 若后端未联查返回elderly对象，则根据elderlyId补充查询一次
    if (!billDetail.value.elderly && billDetail.value.elderlyId) {
      getElderly(billDetail.value.elderlyId).then(res => {
        billDetail.value.elderly = res.data || {}
      }).finally(() => {
        updateDetailData()
      })
      // 继续尝试补齐创建人
      fetchCreator()
      return
    }
    // 补齐创建人
    fetchCreator()
    updateDetailData()
  }).finally(() => {
    // 若还有二次联查（老人/创建人），等一个nextTick再结束loading，避免闪白
    setTimeout(() => { loading.value = false }, 100)
  })
}

// 根据 creator 或 creatorId 兜底查询创建人信息
function fetchCreator() {
  const creatorId = billDetail.value.creatorId || billDetail.value.creator
  // 如果后端已联查提供 billDetail.creatorUser，则直接使用
  if (billDetail.value.creatorUser) return
  if (!creatorId) return
  getUser(creatorId).then(res => {
    billDetail.value.creatorUser = res.data || {}
  }).catch(() => {})
}

// 金额格式化
function formatAmount(amount) {
  if (amount === null || amount === undefined || isNaN(Number(amount))) return '0.00'
  return Number(amount).toFixed(2)
}

// 渲染金额，负数前置 "- "，总计加粗
function renderAmount(value) {
  const num = Number(value || 0)
  const abs = formatAmount(Math.abs(num))
  return num < 0 ? `- ${abs}` : `${abs}`
}

// 格式化账单周期
function formatBillPeriod() {
  const start = parseTime(billDetail.value.billStartTime, '{y}-{m}-{d}')
  const end = parseTime(billDetail.value.billEndTime, '{y}-{m}-{d}')
  return start && end ? `${start} — ${end}` : '--'
}

// 更新明细数据并填充汇总行（从后端获取账单详情数据）
function updateDetailData() {
  const billId = billDetail.value.id
  if (!billId) return

  // 从后端获取账单详情
  listBillDetailByBillId(billId).then(response => {
    const billDetails = response.data || []
    
    // 创建一个映射，方便查找服务内容
    const detailMap = {}
    billDetails.forEach(detail => {
      detailMap[detail.itemName] = detail.serviceContent || ''
    })
    
    // 更新服务内容
    detailData.value[0].content = detailMap['护理费用'] || '—'
    detailData.value[1].content = detailMap['床位费用'] || '—'
    detailData.value[4].content = detailMap['医保支付'] || '——'
    detailData.value[5].content = detailMap['政府补贴'] || '——'
    
    // 继续原有的金额计算逻辑
    const cim = billDetail.value.checkInManagement || {}

    // 费用项（优先账单字段，其次取入住配置里的字段，最后兜底0）
    const nursingFee = Number(billDetail.value.nursingFee ?? cim.nursingFee ?? 0)
    const bedFee = Number(billDetail.value.bedFee ?? cim.bedFee ?? 0)
    const otherFee = Number(billDetail.value.otherFee ?? billDetail.value.otherFeeAmount ?? 0)
    const insurancePayment = Number(billDetail.value.insurancePayment ?? 0)
    const governmentSubsidy = Number(billDetail.value.governmentSubsidy ?? 0)
    const deposit = Number(billDetail.value.deposit ?? cim.deposit ?? 0)

    // 添加项金额
    detailData.value[0].amount = nursingFee
    detailData.value[1].amount = bedFee
    detailData.value[2].amount = otherFee

    const addSubtotal = nursingFee + bedFee + otherFee
    detailData.value[3].amount = addSubtotal

    // 扣减项（以负数显示）
    detailData.value[4].amount = -insurancePayment
    detailData.value[5].amount = -governmentSubsidy
    const minusSubtotal = -(insurancePayment + governmentSubsidy)
    detailData.value[6].amount = minusSubtotal

    // 汇总区（若后端已算好则直接用）
    const monthlyPayable = Number(billDetail.value.monthlyPayable ?? addSubtotal)
    const billAmount = Number(billDetail.value.billAmount ?? addSubtotal)
    const prepaymentAmount = Number(billDetail.value.prepaymentAmount ?? deposit)
    const payableAmount = Number(billDetail.value.payableAmount ?? (billAmount - prepaymentAmount))

    detailData.value[7].amount = monthlyPayable
    detailData.value[8].amount = Number(billDetail.value.currentPayable ?? payableAmount)
    detailData.value[9].amount = deposit
    detailData.value[10].amount = billAmount
    detailData.value[11].amount = -prepaymentAmount
    detailData.value[12].amount = payableAmount
  }).catch(error => {
    console.error('获取账单详情失败', error)
    // 如果获取失败，继续使用原有逻辑（兜底）
    const cim = billDetail.value.checkInManagement || {}

    const nursingFee = Number(billDetail.value.nursingFee ?? cim.nursingFee ?? 0)
    const bedFee = Number(billDetail.value.bedFee ?? cim.bedFee ?? 0)
    const otherFee = Number(billDetail.value.otherFee ?? billDetail.value.otherFeeAmount ?? 0)
    const insurancePayment = Number(billDetail.value.insurancePayment ?? 0)
    const governmentSubsidy = Number(billDetail.value.governmentSubsidy ?? 0)
    const deposit = Number(billDetail.value.deposit ?? cim.deposit ?? 0)

    detailData.value[0].amount = nursingFee
    detailData.value[1].amount = bedFee
    detailData.value[2].amount = otherFee

    const addSubtotal = nursingFee + bedFee + otherFee
    detailData.value[3].amount = addSubtotal

    detailData.value[4].amount = -insurancePayment
    detailData.value[5].amount = -governmentSubsidy
    const minusSubtotal = -(insurancePayment + governmentSubsidy)
    detailData.value[6].amount = minusSubtotal

    const monthlyPayable = Number(billDetail.value.monthlyPayable ?? addSubtotal)
    const billAmount = Number(billDetail.value.billAmount ?? addSubtotal)
    const prepaymentAmount = Number(billDetail.value.prepaymentAmount ?? deposit)
    const payableAmount = Number(billDetail.value.payableAmount ?? (billAmount - prepaymentAmount))

    detailData.value[7].amount = monthlyPayable
    detailData.value[8].amount = Number(billDetail.value.currentPayable ?? payableAmount)
    detailData.value[9].amount = deposit
    detailData.value[10].amount = billAmount
    detailData.value[11].amount = -prepaymentAmount
    detailData.value[12].amount = payableAmount
  })
}

// 计算天数
function calculateDays() {
  if (!billDetail.value.billStartTime || !billDetail.value.billEndTime) {
    return 0
  }
  
  const start = new Date(billDetail.value.billStartTime)
  const end = new Date(billDetail.value.billEndTime)
  const diffTime = Math.abs(end - start)
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1
  return diffDays
}

// 根据状态获取标签类型
function getStatusType(status) {
  switch (status) {
    case '已支付':
      return 'success'
    case '待支付':
      return 'warning'
    case '已关闭':
      return 'danger'
    default:
      return 'info'
  }
}

// 返回上一页
function goBack() {
  router.back()
}

// 组件挂载时获取数据
onMounted(() => {
  getBillDetail()
})
</script>

<style scoped>
.section {
  background: #fff;
  border: 1px solid #ebeef5;
  margin-bottom: 20px;
}

.section-header {
  height: 44px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  border-bottom: 1px solid #ebeef5;
  background: #f5f7fa;
}

.header-badge {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: #e64340;
  color: #fff;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  font-weight: 600;
  font-size: 12px;
}

.header-title {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.info-panel {
  padding: 20px 25px;
}

.info-row {
  display: flex;
  margin-bottom: 18px;
  height: 30px;
  align-items: center;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-item {
  flex: 1;
  display: flex;
  align-items: center;
  height: 100%;
}

.info-item label {
  color: #606266;
  margin-right: 15px;
  font-weight: normal;
  min-width: 120px;
  font-size: 14px;
}

.info-item span {
  color: #303133;
  font-weight: normal;
  font-size: 14px;
}

.amount-value {
  font-weight: 600;
  color: #e64340;
  font-size: 16px;
}

.detail-panel {
  padding: 20px 25px;
}

.el-table {
  border: 1px solid #ebeef5;
  border-radius: 0;
}

.el-table th {
  background-color: #f5f7fa !important;
  font-weight: 500;
  font-size: 14px;
  color: #606266;
  height: 36px;
}

.el-table td {
  height: 36px;
  font-size: 14px;
  color: #303133;
}

.el-table td:first-child {
  color: #606266;
}

.amount-negative {
  color: #303133;
}

.amount-strong {
  font-weight: 600;
}

.summary-section {
  margin-top: 20px;
  border-top: 1px solid #ebeef5;
  padding-top: 20px;
}

.summary-row {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 12px;
  align-items: center;
  height: 30px;
}

.summary-row:last-child {
  margin-bottom: 0;
}

.summary-label {
  color: #606266;
  margin-right: 30px;
  min-width: 100px;
  text-align: right;
  font-size: 14px;
}

.summary-value {
  color: #303133;
  font-weight: normal;
  font-size: 14px;
  min-width: 120px;
  text-align: right;
}

.summary-total {
  font-weight: 600;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #ebeef5;
}

.summary-total .summary-label {
  font-weight: 600;
  color: #303133;
}

.summary-total .summary-value {
  color: #e64340;
  font-size: 16px;
  font-weight: 600;
}

.footer-bar {
  padding: 20px;
  text-align: center;
  margin-top: 30px;
}

.el-tag {
  font-size: 12px;
  height: 24px;
  line-height: 22px;
}

/* 交易状态标签样式 */
.el-tag--success {
  background-color: #f0f9eb;
  border-color: #c2e7b0;
  color: #67c23a;
}

.el-tag--warning {
  background-color: #fdf6ec;
  border-color: #fde2e4;
  color: #e6a23c;
}

.el-tag--danger {
  background-color: #fef0f0;
  border-color: #fde2e4;
  color: #f56c6c;
}
</style>